package com.xz.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xz.usercenter.common.BaseResponse;
import com.xz.usercenter.common.ErrorCode;
import com.xz.usercenter.common.ResultUtils;
import com.xz.usercenter.exception.BusinessException;
import com.xz.usercenter.model.domain.User;
import com.xz.usercenter.model.request.UserLoginRequest;
import com.xz.usercenter.model.request.UserRegisterRequest;
import com.xz.usercenter.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.xz.usercenter.constant.UserConstant.USER_LOGIN_STATUS;

/**
 * @author xuzhou
 * @version 1.0
 */
@Api("用户管理")
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    @ApiOperation("普通用户注册")
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@ApiParam("用户注册信息") @RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String verificationCode = userRegisterRequest.getVerificationCode();
        if (StringUtils.isAllBlank(userAccount, userPassword, checkPassword, verificationCode)) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword, verificationCode);
        return ResultUtils.success(result);
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@ApiParam("用户登录信息") @RequestBody UserLoginRequest userLoginRequest,
                                        HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAllBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    @ApiOperation("用户退出登录")
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }

        if (userService.userLogout(request) != 1) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return ResultUtils.success();
    }

    @ApiOperation("管理员用户搜索")
    @GetMapping("/search")  // required = false  不是必填
    public BaseResponse<IPage<User>> userSearch(@ApiParam("搜索条件") @RequestParam(required = false) String userName,
                                                @ApiParam("每页大小") @RequestParam(defaultValue = "10") long pageSize,
                                                @ApiParam("当前页码") @RequestParam(defaultValue = "1") long pageNum,
                                                HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        LambdaQueryWrapper<User> userQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNoneBlank(userName)) {
            userQueryWrapper.like(User::getUserName, userName);
        }
        IPage<User> userList = userService.page(new Page<>(pageNum, pageSize), userQueryWrapper);
        List<User> list = userList.getRecords().stream().map((user) -> userService.getSafetyUser(user)).collect(Collectors.toList());
        userList.setRecords(list);
        return ResultUtils.success(userList);
    }

    @ApiOperation("用户根据标签搜索用户")
    @GetMapping("/search/tags")
    public BaseResponse<IPage<User>> searchUsers(@ApiParam("标签列表") @RequestParam(required = false) List<String> tagNameList,
                                                 @ApiParam("每页大小") @RequestParam(defaultValue = "10") long pageSize,
                                                 @ApiParam("当前页码") @RequestParam(defaultValue = "1") long pageNum,
                                                 HttpServletRequest request) {
        if (tagNameList != null && CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        IPage<User> userList = userService.searchUsersByTags(tagNameList, pageNum, pageSize);
        return ResultUtils.success(userList);
    }

    /**
     * 更新用户信息接口。
     * 该接口用于更新用户的信息，需要用户提供要更新的信息，并且必须经过身份验证。
     *
     * @param user    包含待更新用户信息的实体对象。
     * @param request 用于获取当前登录用户的请求对象。
     * @return 返回更新操作的结果，通常是一个表示影响行数的整数。
     */
    @ApiOperation("用户信息更新")
    @PutMapping("/update")
    public BaseResponse<Boolean> updateUser(@ApiParam("用户要更新的信息") @RequestBody User user, HttpServletRequest request) {
        //验证参数是否为空
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //鉴权
        User loginUser = userService.getLoginUser(request);
        Boolean result = userService.updateUser(user, loginUser);
        return ResultUtils.success(result);
    }


    /**
     * 批量删除用户接口。
     * 仅允许管理员调用此接口，根据提供的用户ID数组执行删除操作。
     *
     * @param ids     待删除用户的ID列表。
     * @param request 用于鉴权的请求对象。
     * @return 删除操作是否成功的布尔值。
     */
    @ApiOperation("用户删除")
    @DeleteMapping("/delete")
    public BaseResponse<Boolean> userDelete(@ApiParam("用户id 数组，用于批量删除") @RequestParam List<Long> ids,
                                            HttpServletRequest request) {
        // 校验用户ID列表是否为空
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 排除无效的ID（例如0或负数，具体依据业务规则）
        if (ids.stream().anyMatch(id -> id <= 0)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 鉴权：检查当前请求的用户是否为管理员
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        // 执行批量删除操作
        boolean success = userService.removeBatchByIds(ids);
        // 返回操作结果
        return ResultUtils.success(success);
    }


    /**
     * 获取用户当前登录状态
     *
     * @param request
     * @return
     */
    @ApiOperation("获取用户当前登录状态")
    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        Object attribute = request.getSession().getAttribute(USER_LOGIN_STATUS);
        User currentUser = (User) attribute;
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        Long userId = currentUser.getId();
        User user = userService.getById(userId);
        User safetyUser = userService.getSafetyUser(user);
        return ResultUtils.success(safetyUser);
    }


    /**
     * redis 内存不能无限增加，一定要设置过期时间！！！
     * 数据缓存
     */
    @ApiOperation("推荐用户")
    @GetMapping("/recommend")
    public BaseResponse<IPage<User>> recommendUsers(@ApiParam("每页大小") @RequestParam(defaultValue = "10") long pageSize,
                                                    @ApiParam("当前页码") @RequestParam(defaultValue = "1") long pageNum,
                                                    HttpServletRequest request) {
        // 获取当前用户信息
        User loginUser = userService.getLoginUser(request);
        // 获取当前用户ID
        Long currentUserId = loginUser.getId();
        // matching 匹配
        String redisKey = String.format("matching:user:recommend:%s", loginUser.getId());

        ValueOperations valueOperations = redisTemplate.opsForValue();
        //如果有缓存，直接读取
        IPage<User> userPage = (Page<User>) valueOperations.get(redisKey);
        if (userPage != null) {
            return ResultUtils.success(userPage);
        }
        //无缓存，查数据库
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 添加条件，排除当前登录用户
        queryWrapper.ne("id", currentUserId);
        userPage = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
        //写缓存,60s过期
        try {
            valueOperations.set(redisKey, userPage, 60000, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.error("redis set key error ", e);
        }
        return ResultUtils.success(userPage);
    }

    @ApiOperation("编辑距离算法匹配用户")
    @GetMapping("/match")
    public BaseResponse<List<User>> matchUsers(
            @ApiParam("匹配人数") @RequestParam(defaultValue = "10") long num,
            HttpServletRequest request) {
        if (num > 20 || num < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "匹配人数不能超过20");
        }
        User loginUser = userService.getLoginUser(request);
        return ResultUtils.success(userService.matchUsers(num, loginUser));
    }
}
